package com.xq.shop.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xq.shop.po.User;
import com.xq.shop.service.user.IUserService;
import com.xq.shop.util.Const;
import com.xq.shop.util.UserServiceFactory;
import com.xq.shop.vo.RespMsg;
import com.xq.shop.vo.RespMsg.Result;

@Controller
@RequestMapping("/user/")
public class UserCtrl {

	private IUserService userService = UserServiceFactory.getUserService();
	
	@RequestMapping("user_save")
	public ModelAndView save(User user, HttpServletResponse response){
		
		if(StringUtils.isBlank(user.getUsername()) || userService.usernameExists(user.getUsername())){
			//TODO 返回失败提示消息
			return new ModelAndView("home").addObject(new RespMsg(Result.success, "保存失败"));
		}
		userService.save(user);
		return new ModelAndView("home").addObject(new RespMsg(Result.success, "保存成功"));
	}
	
	@RequestMapping("user_check_username")
	@ResponseBody
	public String checkUsername(String username){
		 
		if (StringUtils.isEmpty(username)) return "false";
	    return userService.usernameExists(username) ? "false" : "true";
	}
	
	@RequestMapping("user_information")
	public ModelAndView information(HttpServletRequest request){
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Const.User_Session);
		ModelAndView view = new ModelAndView("user/information");
		view.addObject("user", user);
		return view;
	}
	
	@RequestMapping("user_update")
	public ModelAndView update(User newUser, HttpServletRequest request){
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Const.User_Session);
		user.setName(newUser.getName());
		user.setEmail(newUser.getEmail());
		user.setSex(newUser.getSex());
		user.setBirthday(newUser.getBirthday());
		user.setAddress(newUser.getAddress());
		userService.update(user);
		ModelAndView view = new ModelAndView("user/information");
		view.addObject("user", user);
		return view;
	}
	
	@RequestMapping("user_change_password")
	public ModelAndView changePassword(String passwd, String password, HttpServletRequest request){
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Const.User_Session);
		if(StringUtils.isNotBlank(passwd) && passwd.equals(user.getPassword()) 
				&& StringUtils.isNotBlank(password)){
			
			user.setPassword(password);
			userService.update(user);
		}
		ModelAndView view = new ModelAndView("user/information");
		view.addObject("user", user);
		return view;
	}
}